#include "itemdialog.h"
#include "ui_itemdialog.h"

#include <QSqlTableModel>
#include <QSqlRecord>
#include <QModelIndex>
#include <QModelIndexList>

#include <QCompleter>

ItemDialog::ItemDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ItemDialog)
{
    ui->setupUi(this);

    this->loadData();
}

ItemDialog::~ItemDialog()
{
    delete ui;
}

void ItemDialog::accept()
{
    if(ui->name_lineEdit->text().isEmpty() || ui->measure_comboBox->currentText().isEmpty()){
        return;
    }
    QDialog::accept();
}

void ItemDialog::loadData()
{
    QSqlTableModel* model = new QSqlTableModel(ui->measure_comboBox);
    model->setTable("items");
    model->select();

    QStringList wordList;
    for(int i=0; i<model->rowCount(); i++){
        QSqlRecord record = model->record(i);
        if(record.isEmpty()) break;
        wordList << record.value("measure").toString();
    }
    wordList.removeDuplicates();
    QCompleter *completer = new QCompleter(wordList, this);
    completer->setCompletionMode(QCompleter::PopupCompletion);
    ui->measure_comboBox->clear();
    ui->measure_comboBox->setCompleter(completer);
    ui->measure_comboBox->addItems(wordList);
    delete model;
}

QString ItemDialog::getName() const
{
    return ui->name_lineEdit->text();
}

QString ItemDialog::getMeasure() const
{
    return ui->measure_comboBox->currentText();
}

double ItemDialog::getPrice() const
{
    return ui->price_doubleSpinBox->value();
}

void ItemDialog::setItem(const int item_id)
{
    setWindowTitle(tr("Item (edit)"));
    QSqlTableModel* model = new QSqlTableModel(this);
    model->setTable("items");
    model->select();
    QModelIndexList item = model->match(model->index( 0, model->fieldIndex("id")), Qt::DisplayRole, item_id,  1, Qt::MatchExactly);
    ui->measure_comboBox->setCurrentIndex(ui->measure_comboBox->findData(model->data(model->index(item[0].row(), model->fieldIndex("measure"))).toString(), Qt::EditRole));
    ui->name_lineEdit->setText(model->data(model->index(item[0].row(), model->fieldIndex("name"))).toString());
    ui->price_doubleSpinBox->setValue(model->data(model->index(item[0].row(), model->fieldIndex("price"))).toDouble());
    delete model;
}
